var StaffList = function() {
	let
	AUTHORITY = $("#authority").attr("content");
	var initTable = function() {
		// 渲染列表
		var oTable = $("#table")
				.DataTable(
						{
							"bAutoWidth" : true,
							// "bProcessing" : true,
							"bFilter" : true,
							// "bStateSave" : true,
							// "sPaginationType" : "full_numbers",
							"aaSorting" : [ [ 0, 'desc' ] ],
							bSort : false,
							"oLanguage" : { // 汉化
								"sProcessing" : "正在加载数据...",
								"sLengthMenu" : "显示_MENU_条",
								"sZeroRecords" : "没有您要搜索的内容",
								"sInfo" : "从_START_ 到 _END_ 条记录——总记录数为 _TOTAL_ 条",
								"sInfoEmpty" : "记录数为0",
								"sInfoFiltered" : "(全部记录数 _MAX_  条)",
								"sInfoPostFix" : "",
								"sSearch" : "搜索",
								"sUrl" : "",
								"oPaginate" : {
									"sFirst" : "首页",
									"sPrevious" : " 上一页 ",
									"sNext" : " 下一页 ",
									"sLast" : " 末页 "
								}
							},
							"aoColumns" : [
									{
										"mData" : "userName",
									},
									{
										"mData" : "staffRealName",
									},
									{
										"mData" : "staffDepartment",
									},
									{
										"mData" : "staffPosition",
									},
									{
										"mData" : "staffPhone",
									},
									{
										"mData" : "isAdviser",
                                        "mRender":function (value, method, row) {
                                            return value==1?"是":"否";
                                        }
									},
									{
										"mData" : "isTeacher",
                                        "mRender":function (value, method, row) {
											return value==1?"是":"否";
										}
									},
									{
										"mData" : "staffPermission",
									},
									{
										"mData" : "staffState",
                                        "mRender":function (value, method, row) {
                                            switch (value){
                                                case 1: return "在职";
                                                case 5: return "离职";
                                                case 2: return "兼职";
                                                case 3: return "实习";
                                                case 4: return "冻结";
                                                default: return "未知状态"

                                            }
                                        }
									},
									{
										"mData" : function(source, type, val) {
											return source;
										},
										"mRender" : function(value, method, row) {
											var btn = '';
											let
											view = '<a class="btn green staff_view"  data-id="'
													+ value.id
													+ '"><i class="icon-eye-open"></i> 查看</a>';
											let
											edit = '<a class="btn purple staff_edit" style="margin-left:10px;" data-id="'
													+ value.id
													+ '"><i class="icon-edit"></i> 编辑</a>';
											let
											del = '<a class="btn black staff_delete" style="margin-left:10px;" data-id="'
													+ value.id
													+ '"><i class="icon-trash"></i> 删除</a>';

											if (AUTHORITY
													.includes("PERMISSION_STAFF_VIEW")) {
												btn += view;
											}
											if (AUTHORITY
													.includes("PERMISSION_STAFF_EDIT")) {
												btn += edit;
											}
											if (AUTHORITY
													.includes("PERMISSION_STAFF_DELETE")) {
												btn += del;
											}
											return btn;
										}
									} ],
							bServerSide : true,
							sAjaxSource : "/stafflist",
							fnServerData : function(source, data, fnCallBack) {
								// alert("data:"+JSON.stringify(data));
								$.ajax({
									type : "POST",
									dataType : "json",
									url : source,
									data : "param=" + JSON.stringify(data)+ "&" + $("#staff_search_form").serialize(),
									// beforeSend:beginWait(),
									success : function(d) {
										if (d.retCode != "1")
											// bootbox.alert(d.retMsg);
											alert(d.retMsg);
										else {
											// $("#total").html(d.retObj.iTotalRecords);
											fnCallBack(d.retObj);
										}
									},
									failure : function(d) {
										// bootbox.alert("服务器无响应");
										alert("服务器无响应");
									},
								// complete:clearWait()
								});
							}
						});

		jQuery('#table_wrapper .dataTables_filter input').addClass(
				"m-wrap small"); // modify table search input
		jQuery('#table_wrapper .dataTables_length select').addClass(
				"m-wrap small"); // modify table per page dropdown
		jQuery('#table_wrapper .dataTables_length select').select2();

		// 显示／隐藏指定列
		$('#table_column_toggler input[type="checkbox"]').change(function() {
			var column = oTable.column($(this).attr('data-column'));
			column.visible(!column.visible());
		});

		$("#btn_staff_search").click(function (e) {
			e.preventDefault();

            oTable.draw(true);

        });
	};

	var event = function() {
		// 1.删除
		$("#table").on("click", "td a.staff_delete", function() {
			var roleId = $(this).attr("data-id");
			layer.confirm('您确定要删除吗，删除后不可恢复？', {
				title : '删除员工',
				btn : [ '是', '否' ],
				btnAlign : 'c'
			// 按钮
			}, function() {
				deleteStaff(roleId);
			}, function() {
				
			});
		});
		// 2.编辑
		$("#table").on("click", "td a.staff_edit", function() {
			var roleId = $(this).attr("data-id");
			layer.open({
				title : '编辑员工',
				btn : [ '是', '否' ],
				type : 2,
				skin : 'layui-layer-rim', // 加上边框
				area : [ "90%", "90%" ],
				content : "/staffedit/" + roleId,
				yes : function(index, layerno) {
					var body = layer.getChildFrame('body', index);

					var $form = body.find("#staff_edit_form");

					if (!$form.valid()) {
						$form.find("label.error").hide();
						return;
					}

					var form_data = $form.serializeArray();
					//alert(JSON.stringify(form_data));
					var post_data = {};
					$.map(form_data, function(n, i) {
						
						var key=n['name'];
						var value=n['value'];
						if(key&&post_data.hasOwnProperty(key) ){
							let originValue=post_data[key];
							let newValue=originValue+","+value;
							post_data[key]=newValue;
						}else{
							post_data[key] = value;
						}

                        post_data.userName=$form.find("input[name='userName']").val();
						
					});
					// alert(JSON.stringify(post_data));
//					//处理 拥有学员
//					var valArr = new Array();
//					body.find("#has_student input[type='checkbox']").each(function(i) {
//						if ($(this).is(':checked')) {
//							valArr.push($(this).val());
//						}
//					});
//					var vals = valArr.join(',');// 转换为逗号隔开的字符串
//					
//					post_data.hasStudent=vals;
//					//
					submitForm(JSON.stringify(post_data), "/staffedit/"+roleId);
				},
				btn2 : function(index, layerno) {

				}
			});

		});

		// 3.添加员工
		$("#btn_add").click(function(e) {
			e.preventDefault();

			var roleId = $(this).attr("data-id");
			layer.open({
				title : '添加员工',
				btn : [ '是', '否' ],
				type : 2,
				skin : 'layui-layer-rim', // 加上边框
				// area: ['620px', 'auto'], //宽高
				area : [ "90%", "90%" ],
				content : "/staffadd/",
				scrollbar : false,
				yes : function(index, layerno) {
					var body = layer.getChildFrame('body', index);

					var $form = body.find("#staff_add_form");

					if (!$form.valid()) {
						$form.find("label.error").hide();
						return;
					}

					var form_data = $form.serializeArray();

					var post_data = {};

					$.map(form_data, function(n, i) {
						var key=n['name'];
						var value=n['value'];
						if(key&&post_data.hasOwnProperty(key) ){
							let originValue=post_data[key];
							let newValue=originValue+","+value;
							post_data[key]=newValue;
						}else{
							post_data[key] = value;
						}
					});
					// alert(JSON.stringify(post_data));
					// console.log(JSON.stringify(post_data));
					submitForm(JSON.stringify(post_data), "/staffadd");

				},
				btn2 : function(index, layerno) {
					// layer.msg("取消了", {
					// icon : 2
					// });
				}
			});
		});

		//4.查看
        $("#table").on("click", "td a.staff_view", function() {
            var roleId = $(this).attr("data-id");
            layer.open({
                title : '查看员工信息',
                type : 2,
                skin : 'layui-layer-rim', // 加上边框
                area : [ "90%", "90%" ],
				scrollbar:false,
                content : "/staffview/" + roleId
            });

        });
	};
	function deleteStaff(roleId) {
		$.ajax({
			type : "DELETE",
			dataType : "json",
			url : "/staffdelete/" + roleId,
		}).done(function(data) {
			if (data && data.retCode == 1) {
				layer.msg(data.retMsg, {
					icon : 1
				});
				setTimeout('$("#table").DataTable().ajax.reload();', 800)

			} else {
				var s = layer.msg(data.retMsg, {
					icon : 2
				});
				layer.close(s);
			}
		}).fail(function(d) {
			layer.msg("服务器无响应", {
				icon : 2
			});

		});
	}
	/**
	 * 提交表单
	 * 
	 * @param data
	 */
	function submitForm(data, url) {
		$
				.ajax({
					type : "POST",
					dataType : "json",
					url : url,
					contentType : "application/json;charset=utf-8",
					data : data
				})
				.done(
						function(data) {
							if (data && data.retCode == 1) {
								layer.msg(data.retMsg, {
									icon : 1
								});

								setTimeout(
										'layer.closeAll();$("#table").DataTable().ajax.reload();',
										800);

							} else {
								var s = layer.msg(data.retMsg, {
									icon : 3
								});
								layer.close(s);
							}
						}).fail(function(d) {
					layer.msg("服务器无响应");

				});
	}

	return {
		init : function() {

			initTable();
			event();
		}
	};

}();